package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.operator.Between;
import com.ejlchina.searcher.operator.Contain;
import com.ejlchina.searcher.operator.Equal;
import com.ejlchina.searcher.util.MapUtils;
import com.sky.constant.MessageConstant;
import com.sky.constant.OrderConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.ServiceException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.*;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.web.page.TableSupport;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author tzl
 * @Date 2023-07-26 15:59:07  星期三
 * @Description: 订单模块业务实现类接口
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private BeanSearcher beanSearcher;

    @Autowired
    private WeChatPayUtil weChatPayUtil;


    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 历史订单查询
     * @param status 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    @Override
    public SearchResult<OrderVO> selectHistoryOrders(Integer status) {
        Long userId = BaseContext.getCurrentUserId();
        Map<String, Object> build = MapUtils.builder()
                .page(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize())
                .field(Orders::getUserId,userId).op(Equal.class)
                .field(Orders::getStatus,status).op(Equal.class)
                .orderBy(Orders::getOrderTime).desc()
                .build();
        SearchResult<Orders> search = beanSearcher.search(Orders.class, build);

        List<OrderVO> result = new ArrayList<>();
        List<Orders> dataList = search.getDataList();
        if (!CollectionUtils.isEmpty(dataList)){
            dataList.forEach(item->{
                Long orderId = item.getId();// 订单id

                // 查询订单明细
                Map<String, Object> build1 = MapUtils.builder()
                        .field(OrderDetail::getOrderId,orderId).op(Equal.class)
                        .build();
                List<OrderDetail> orderDetails = beanSearcher.searchAll(OrderDetail.class, build1);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                result.add(orderVO);
            });
        }

        SearchResult<OrderVO> searchResult = new SearchResult<>(result);
        searchResult.setTotalCount(search.getTotalCount());

        return searchResult;
    }




    /**
     * 订单搜索
     *
     * @param dto 订单信息
     * @return
     */
    @Override
    public SearchResult<OrderVO> selectlOrders(OrdersDTO dto) {

        Map<String, Object> build = MapUtils.builder()
                .page(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize())
                .field(Orders::getNumber,dto.getNumber()).op(Contain.class)
                .field(Orders::getPhone,dto.getPhone()).op(Contain.class)
                .field(Orders::getStatus,dto.getStatus()).op(Equal.class)
                .field(Orders::getOrderTime,dto.getBeginTime(),dto.getEndTime()).op(Between.class)
                .build();
        SearchResult<Orders> search = beanSearcher.search(Orders.class, build);
        List<OrderVO> result = new ArrayList<>();
        List<Orders> dataList = search.getDataList();
        if (!CollectionUtils.isEmpty(dataList)){
            dataList.forEach(item->{
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item, orderVO);
                String orderDishes = getOrderDishesStr(item);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                result.add(orderVO);
            });
        }

        SearchResult<OrderVO> searchResult = new SearchResult<>(result);
        searchResult.setTotalCount(search.getTotalCount());
        return searchResult;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        // 查询订单明细
        Map<String, Object> build1 = MapUtils.builder()
                .field(OrderDetail::getOrderId,orders.getId()).op(Equal.class)
                .build();
        List<OrderDetail> orderDetailList = beanSearcher.searchAll(OrderDetail.class, build1);

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Map<String, Object> build = MapUtils.builder()
                .page(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize())
                .field(Orders::getStatus,OrderConstant.TO_BE_CONFIRMED).op(Equal.class)
                .build();
        int toBeConfirmed = beanSearcher.searchCount(Orders.class, build).intValue();

        Map<String, Object> build1 = MapUtils.builder()
                .page(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize())
                .field(Orders::getStatus,OrderConstant.CONFIRMED).op(Equal.class)
                .build();
        int confirmed = beanSearcher.searchCount(Orders.class, build1).intValue();

        Map<String, Object> build2 = MapUtils.builder()
                .page(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize())
                .field(Orders::getStatus,OrderConstant.DELIVERY_IN_PROGRESS).op(Equal.class)
                .build();
        int deliveryInProgress = beanSearcher.searchCount(Orders.class, build2).intValue();

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     *
     * @param id 订单id
     * @return
     */
    @Override
    public OrderVO selectOrderVOById(Long id) {
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,id).op(Equal.class)
                .build();
        Orders orders = beanSearcher.searchFirst(Orders.class, build);

        Map<String, Object> build1 = MapUtils.builder()
                .field(OrderDetail::getOrderId,id).op(Equal.class)
                .build();
        List<OrderDetail> orderDetails = beanSearcher.searchAll(OrderDetail.class, build1);



        OrderVO orderVO = new OrderVO();
        BeanCopyUtil.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 用户下单
     * @param dto 订单信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO dto) {
        //判断地址薄是否为空，
        Map<String, Object> build =
                MapUtils.builder()
                        .field(AddressBook::getId,dto.getAddressBookId()).op(Equal.class)
                        .build();
        AddressBook addressBook = beanSearcher.searchFirst(AddressBook.class, build);
        if (Objects.isNull(addressBook)) {
            throw new ServiceException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车信息是否为空
        Long userId = BaseContext.getCurrentUserId();
        Map<String, Object> build1 =
                MapUtils.builder()
                        .field(ShoppingCart::getUserId,userId).op(Equal.class)
                        .build();
        List<ShoppingCart> shoppingCartList = beanSearcher.searchAll(ShoppingCart.class, build1);
        if (CollectionUtils.isEmpty(shoppingCartList)) {
            throw new ServiceException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //进行下单操作
        Orders orders = new Orders();
        BeanCopyUtil.copyProperties(dto,orders);
        orders.setUserId(userId);
        orders.setOrderTime(DateUtils.getNowDate());
        orders.setPayStatus(OrderConstant.UN_PAID);
        orders.setStatus(OrderConstant.PENDING_PAYMENT);
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1L); // 指定 workerId
        orders.setNumber(String.valueOf(idWorker.nextId()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getProvinceName()+ addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setUserName(addressBook.getConsignee());
        orders.setCreateBy(BaseContext.getCurrentUserName());
        orders.setCreateTime(DateUtils.getNowDate());
        orders.setUpdateBy(BaseContext.getCurrentUserName());
        orders.setUpdateTime(DateUtils.getNowDate());
        orderMapper.insert(orders);

        //添加订单明细表
        shoppingCartList.forEach(item ->{
            OrderDetail orderDetail = new OrderDetail();
            BeanCopyUtil.copyProperties(item,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetail.setCreateBy(BaseContext.getCurrentUserName());
            orderDetail.setCreateTime(DateUtils.getNowDate());
            orderDetail.setUpdateBy(BaseContext.getCurrentUserName());
            orderDetail.setUpdateTime(DateUtils.getNowDate());
            orderDetailMapper.insert(orderDetail);
        });

        //清空购物车
        UpdateWrapper<ShoppingCart> wrapper = new UpdateWrapper<>();
        wrapper.in("user_id",userId);
        wrapper.set("del_flag","2");
        wrapper.set("update_time", DateUtils.getNowDate());
        wrapper.set("update_by", BaseContext.getCurrentUserName());
        shoppingCartMapper.update(null,wrapper);

        //封装返回对象
        OrderSubmitVO result = new OrderSubmitVO();
        result.setId(orders.getId());
        result.setOrderTime(orders.getOrderTime());
        result.setOrderNumber(orders.getNumber());
        result.setOrderAmount(orders.getAmount());
        return result;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        User user = beanSearcher.searchFirst(User.class, MapUtils.builder().field(User::getId, userId).op(Equal.class).build());


//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal("0.01"), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new ServiceException("该订单已支付");
//        }

        OrderPaymentVO vo = new OrderPaymentVO();
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1);
        vo.setNonceStr(String.valueOf(snowflakeIdWorker.nextId()));
        vo.setPaySign(RandomCharDataUtil.createRandomCharData(12));
        vo.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        vo.setSignType("MD5");
        vo.setPackageStr("4B3B3DC35414AD50B1B755BAF8DE9CC7CF407606");


        //未接入微信支付，自动设置支付成功
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 商户订单号
     */
    public void paySuccess(String outTradeNo) {

        Long userId = BaseContext.getCurrentUserId();

        // 根据订单号查询订单
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getNumber,outTradeNo).op(Equal.class)
                .field(Orders::getUserId,userId).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(OrderConstant.TO_BE_CONFIRMED);
        orders.setPayStatus(OrderConstant.PAID);
        orders.setCheckoutTime(DateUtils.getNowDate());
        orders.setUpdateBy(BaseContext.getCurrentUserName());
        orders.setUpdateTime(DateUtils.getNowDate());
        orderMapper.updateById(orders);


        //通过webSocketServer给客户端发送消息
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", ordersDB.getId());
        map.put("type", 1); //1为来单提醒，2为催单
        map.put("content", "订单号："+outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 用户取消订单
     *
     * @return
     */
    @Override
    public int userCancelById(Long id) {
        Long userId = BaseContext.getCurrentUserId();
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,id).op(Equal.class)
                .field(Orders::getUserId, userId).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        // 校验订单是否存在
        if (Objects.isNull(ordersDB)) {
            throw new ServiceException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new ServiceException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(OrderConstant.TO_BE_CONFIRMED)) {
            /*//调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/

            //支付状态修改为 退款
            orders.setPayStatus(OrderConstant.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(OrderConstant.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(DateUtils.getNowDate());
        orders.setUpdateBy(BaseContext.getCurrentUserName());
        orders.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateById(orders);
    }

    /**
     * 再来一单
     * @param id 订单id
     * @return
     */
    @Override
    public int repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentUserId();
        Map<String, Object> build = MapUtils.builder()
                .field(OrderDetail::getOrderId,id).op(Equal.class)
                .build();
        List<OrderDetail> orderDetailList = beanSearcher.searchAll(OrderDetail.class, build);
        if (CollectionUtils.isEmpty(orderDetailList)){
            throw new ServiceException("订单详情不存在");
        }

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanCopyUtil.copyProperties(item, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateBy(BaseContext.getCurrentUserName());
            shoppingCart.setCreateTime(DateUtils.getNowDate());
            shoppingCart.setUpdateBy(BaseContext.getCurrentUserName());
            shoppingCart.setUpdateTime(DateUtils.getNowDate());
            return shoppingCart;
        }).collect(Collectors.toList());

        boolean b = shoppingCartService.saveBatch(shoppingCartList);
        if (b) {
            return 1;
        }else {
            return 0;
        }
    }


    /**
     * 客户催单
     * @param id 订单id
     * @return
     */
    @Override
    public void reminder(Long id) {
        Long userId = BaseContext.getCurrentUserId();
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,id).op(Equal.class)
                .field(Orders::getUserId, userId).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        // 校验订单是否存在
        if (Objects.isNull(ordersDB)) {
            throw new ServiceException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 3) {
            throw new ServiceException(MessageConstant.ORDER_STATUS_REMINDER);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("orderId", ordersDB.getId());
        map.put("type", 2); //1为来单提醒，2为催单
        map.put("content", "订单号："+ordersDB.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 接单
     *
     * @return
     */
    @Override
    public int confirm(OrdersDTO dto) {
        Orders orders = new Orders();
        orders.setId(dto.getId());
        orders.setStatus(OrderConstant.CONFIRMED);
        orders.setUpdateBy(BaseContext.getCurrentName());
        orders.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateById(orders);
    }

    /**
     * 拒单
     *
     * @return
     */
    @Override
    public int rejection(OrdersDTO dto) {
        // 根据id查询订单
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,dto.getId()).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(OrderConstant.TO_BE_CONFIRMED)) {
            throw new ServiceException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (Objects.equals(payStatus, OrderConstant.PAID)) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(OrderConstant.CANCELLED);
        orders.setCancelReason(dto.getRejectionReason());
        orders.setRejectionReason(dto.getRejectionReason());
        orders.setCancelTime(DateUtils.getNowDate());
        orders.setUpdateBy(BaseContext.getCurrentName());
        orders.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateById(orders);
    }


    /**
     * 取消订单
     *
     * @return
     */
    @Override
    public int cancel(OrdersDTO dto) {
        // 根据id查询订单
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,dto.getId()).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (Objects.equals(payStatus, OrderConstant.PAID)) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(OrderConstant.CANCELLED);
        orders.setCancelReason(dto.getCancelReason());
        orders.setCancelTime(DateUtils.getNowDate());
        orders.setUpdateBy(BaseContext.getCurrentName());
        orders.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateById(orders);
    }


    /**
     * 派送订单
     *
     * @return
     */
    @Override
    public int delivery(Long id) {
        // 根据id查询订单
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,id).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(OrderConstant.CONFIRMED)) {
            throw new ServiceException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(OrderConstant.DELIVERY_IN_PROGRESS);
        orders.setUpdateBy(BaseContext.getCurrentName());
        orders.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateById(orders);
    }

    /**
     * 完成订单
     *
     * @param id 订单id
     */
    @Override
    public int complete(Long id) {
        // 根据id查询订单
        Map<String, Object> build = MapUtils.builder()
                .field(Orders::getId,id).op(Equal.class)
                .build();
        Orders ordersDB = beanSearcher.searchFirst(Orders.class, build);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(OrderConstant.DELIVERY_IN_PROGRESS)) {
            throw new ServiceException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(OrderConstant.COMPLETED);
        orders.setDeliveryTime(DateUtils.getNowDate());
        orders.setUpdateBy(BaseContext.getCurrentName());
        orders.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateById(orders);
    }
}
